// 处理下数据，保证列表有pageSize条数据，防止内容过多卡顿
import { ref } from 'vue'

export default function () {
  let loading = false
  let pageSize = 20
  let startIndex = 0
  let list = []
  let scrollTop
  let listLength = 0
  let loadingRef
  const virtualList = ref([])

  const initVirtualList = (loadingRef_v, scrollTop_v, value) => {
    // 初始化
    startIndex = 0
    // 接收
    loadingRef = loadingRef_v
    scrollTop = scrollTop_v
    list = value
    listLength = list.length
    // 初始化，前x条数据
    virtualList.value = list.slice(0, pageSize)
  }

  // 滑动到顶部
  const reachTop = () => {
    if (listLength <= pageSize || loading || startIndex == 0) return
    startIndex -= pageSize - 10
    if (startIndex <= 0) {
      startIndex = 0
    }
    startLoading(startIndex)
    // const startIndex_v = startIndex == 0 ? 0 : startIndex + 4
    virtualList.value = list.slice(startIndex, startIndex + pageSize)
  }
  // 滑动到底部
  const reachBottom = () => {
    if (listLength <= pageSize || loading || startIndex >= listLength - pageSize) return
    startLoading()
    startIndex += pageSize - 7
    if (startIndex >= listLength - pageSize) {
      startIndex = listLength - pageSize
    }
    // const startIndex_v = startIndex == 0 ? 0 : startIndex - 5
    virtualList.value = list.slice(startIndex, startIndex + pageSize)
    // virtualList.value = list.slice(startIndex_v, startIndex + pageSize)
    // console.log("🐳 > reachBottom > startIndex_v:", startIndex_v,startIndex + pageSize, virtualList.value );
  }

  // 开启加载提示
  const startLoading = (startIndex) => {
    scrollTop.value = -1
    loading = true
    loadingRef.value.showLoading()
    setTimeout(() => {
      scrollTop.value = startIndex == 0 ? 0 : 150
    }, 500)
    setTimeout(() => {
      loadingRef.value.hideLoading()
      loading = false
    }, 1000)
  }

  return {
    virtualList,
    initVirtualList,
    reachTop,
    reachBottom,
  }
}
